import { Button, message, Table } from 'antd';
import React, {
  createRef,
  memo,
  useCallback,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';
import { request } from 'umi';

let start = 1;
const App: React.FC<cType.tableProTp> = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [data, setdata] = useState([]);
  const column = [...props.tableOption.columns];
  const [total, settotal] = useState(0);
  const getUserTable = useCallback(async (pageOption?: cType.pageOptionType) => {
    let res = await request(props.tableOption.getApi, {
      params: { limit: pageOption?.limit, start: pageOption?.start },
    });
    if (res?.flag) {
      if (props.tableOption.tableAfterGet) res.data.dataList = props.tableOption.tableAfterGet(res.data.dataList);
      setdata(res.data.dataList);
      settotal(res.data.total);
    }
  }, []);
  function edit(rec){
    props.showModal(rec)
  }
  async function deleteData(record) {
    const msg = await request(props.tableOption.getApi + '/' + record.id, { method: 'delete' });
    if (msg.flag) {
      messageApi.success('删除成功!');
      getUserTable({ limit: 10, start: start });
    }
  }
  if (props.tableOption.handleTable) {
    column.push({
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <>
          {!props.tableOption.hideEdit && (
            <Button style={{ marginRight: '20px' }} onClick={()=>edit(record)}>
              编辑
            </Button>
          )}
          <Button onClick={() => deleteData(record)}>删除</Button>
          {props.tableOption.moreBtn && props.tableOption.moreBtn(record)}
        </>
      ),
    });
  }

  const onChange = (pagination: any) => {
    // setstartd(pagination.current)
    start = pagination.current;
    getUserTable({ start: pagination.current });
  };

  useEffect(() => {
    getUserTable({ limit: 10, start: 1 });
  }, []);

  const tableInRef: any = createRef();

  useImperativeHandle(ref, () => ({ ref: tableInRef, getUserTable }));
  return (
    <>
      {contextHolder}
      <Table
        scroll={{ x: '100%' }}
        ref={tableInRef}
        onChange={onChange}
        pagination={{ defaultCurrent: 1, total: total }}
        rowKey={(row) => row.id}
        columns={column}
        dataSource={data}
      />
    </>
  );
});
export default memo(App);
